import 'package:flutter/material.dart';
import 'package:flutter_account_book/pages/record/widget/icon_list.dart';
import 'package:flutter_account_book/utils/alert.dart';
import 'package:flutter_account_book/utils/db/db_helper.dart';
import 'package:flutter_account_book/utils/db/entities/record_type.dart';
import 'package:flutter_account_book/widgets/custom_icon.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';

import '../logic.dart';

class AddForm extends StatefulWidget {
  const AddForm({Key? key}) : super(key: key);

  @override
  State<AddForm> createState() => _AddFormState();
}

class _AddFormState extends State<AddForm> {
  final _logic = Get.find<RecordTypeLogic>();
  final textController = TextEditingController();

  RecordType recordType = RecordType();
  int isIncome = 0;
  RxInt type = 0.obs;
  RxString iconStr = "".obs;
  RxString iconName = "名称".obs;
  RxInt backgroundColorHex = 0xFFdc3023.obs;
  RxInt textColorHex = 0xFFFFFFFF.obs;

  @override
  void initState() {
    super.initState();
    if (Get.arguments != null) {
      if (Get.arguments["recordType"] != null) {
        recordType = Get.arguments["recordType"] as RecordType;
        iconStr.value = recordType.iconPath ?? "";
        type.value = recordType.type;
        textController.text = recordType.name;
        iconName.value = recordType.name;
      }
      isIncome = Get.arguments["isIncome"] as int;
    }
    _logic.getAllIcons().then((list) {
      if (iconStr.isEmpty) {
        iconStr.value = list.first;
      }
    });
  }

  @override
  void dispose() {
    textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Add Form'),
        ),
        body: Container(
          // color: Colors.red,
          padding: EdgeInsets.all(16),
          child: Form(
              child: Column(
            children: [
              Row(children: [
                InkWell(
                    onTap: () {
                      if (type.value == 0) {
                        Get.to<String>(IconList())?.then((iconPath) {
                          if (iconPath != null && iconPath.isNotEmpty) {
                            iconStr.value = iconPath;
                          }
                        });
                      }
                    },
                    child: Obx(() => type.value == 1
                        ? CustomIcon.text(
                            iconName.value,
                            size: CustomIconSize.large,
                            backgroundColor: Color(backgroundColorHex.value),
                            color: Color(textColorHex.value),
                          )
                        : iconStr.value.isEmpty
                            ? Container()
                            : CustomIcon.asset(iconStr.value,
                                size: CustomIconSize.large,
                                backgroundColor:
                                    Color(backgroundColorHex.value),
                                color: Color(textColorHex.value)))),
                SizedBox(width: 10),
                TextButton(
                    onPressed: () async {
                      Color? color = await showColorPickerDialog(
                          context: context,
                          title: "修改背景颜色",
                          initColor: Color(backgroundColorHex.value));
                      if (color != null) {
                        backgroundColorHex.value = color.value;
                      }
                    },
                    child: Text('修改背景颜色')),
                TextButton(
                    onPressed: () async {
                      Color? color = await showColorPickerDialog(
                          context: context,
                          title: "修改字体颜色",
                          initColor: Color(textColorHex.value));
                      if (color != null) {
                        textColorHex.value = color.value;
                      }
                    },
                    child: Text('修改字体颜色'))
              ]),
              Row(
                children: [
                  Obx(() => Checkbox(
                      value: type.value == 1,
                      onChanged: (value) {
                        type.value = value! ? 1 : 0;
                      })),
                  Text("是否文本头像")
                ],
              ),
              SizedBox(height: 20),
              TextFormField(
                controller: textController,
                onChanged: (text) {
                  iconName.value = text;
                },
                validator: (context) {
                  if (context == null || context.isEmpty) {
                    return '请输入名称';
                  }
                  if (_logic.state.list
                          .indexWhere((element) => element.name == context) !=
                      -1) {
                    return '名称已存在';
                  }
                  return null;
                },
                decoration: InputDecoration(
                  labelText: '名称',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                  onPressed: () async {
                    if (textController.text.isEmpty) {
                      return;
                    }
                    recordType.name = textController.text;
                    recordType.iconPath =
                        type.value == 0 ? iconStr.value : iconName.value;
                    recordType.type = type.value;
                    recordType.isIncome = isIncome;
                    recordType.order =
                        await DbHelper.helper.recordTypeDao.maxOrder();
                    recordType.backgroundColorHex = backgroundColorHex.value;
                    recordType.textColorHex = textColorHex.value;
                    recordType.save();
                    Get.back();
                  },
                  child: Text('保存'))
            ],
          )),
        ));
  }
}
